var uuidV4 = require('uuid/v4');
var Eventproxy = require('eventproxy');
var logger = require('../common/logger');
var models = require('../models');
var tools = require('../common/tools');

exports.newEvent = function newEvent(req, res, next) {
  var ep = new Eventproxy();
  ep.fail(next);
  var data = req.body;
  logger.info(data);

  var eventUUID = req.params.uuid;

  ep.all('missing', function (attrs) {
    if (attrs.length) {
      return res.send_data({
        code: 400,
        message: '缺少字段' + attrs
      });
    }
  });
  var missingAttrs = tools.checkMissingAttr(data, ['name', 'sdate', 'edate']);
  if (missingAttrs.length) {
    return ep.emit('missing', missingAttrs);
  }

  if (!data.name) {
    return res.send_data({
      code: 400,
      message: '赛事名称不能为空!'
    });
  }
  data.name = data.name.trim();

  if (eventUUID) { // 编辑赛事
    models.event.update(data, {
      where: {
        uuid: eventUUID
      }
    }).then(function(returnData) {
      return res.send_data();
    });
  } else {
    models.event.create(data).then(function(returnData) {
      return res.send_data();
    });
  }
};

exports.getEvents = function getEvents(req, res, next) {
  var reqQuery = req.query;
  var page = parseInt(reqQuery.page, 10) || 1;
  page = page > 0 ? page : 1;
  var limit = models.event.pageLimit(Number(reqQuery.limit));
  var offset = models.event.pageOffset(page, limit);

  var condition = {
    offset: offset,
    limit: limit,
    where: {}
  };

  models.event.findAndCountAll(condition).then(function(returnEvents) {
    return res.send_data({
      entities: returnEvents.rows,
      total_pages: models.event.totalPages(returnEvents.count, limit),
      current_page: page
    })
  });
};

exports.delEvent = function delEvent(req, res) {
  var data = req.body;

  var eventUUID = req.params.uuid;

  models.event.destroy({
    where: {
      uuid: eventUUID
    }
  }).then(function() {
    return res.send_data();
  });
};

exports.enableEvent = function enableEvent(req, res) {
  var data = req.body;

  var eventId = req.params.uuid;

  models.event.update({
    status: 1
  }, {
    where: {
      uuid: eventId
    }
  }).then(function() {
    return res.send_data();
  });
};

exports.disableEvent = function disableEvent(req, res) {
  var data = req.body;

  var eventId = req.params.uuid;

  models.event.update({
    status: 0
  }, {
    where: {
      uuid: eventId
    }
  }).then(function() {
    return res.send_data();
  });
};

exports.getEventByUUID = function getEventByUUID(req, res) {
  var eventUUID = req.params.uuid;

  models.event.findOne({
    where: {
      uuid: eventUUID
    }
  }).then(function(returnEvent) {
    return res.send_data({
      entities: returnEvent
    });
  });
};
